package com.writing.controller;

import com.writing.common.Result;
import com.writing.service.ImageGenerationService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 图像生成控制器
 */
@RestController
@RequestMapping("/images")
@RequiredArgsConstructor
public class ImageGenerationController {

    private final ImageGenerationService imageGenerationService;

    /**
     * 生成图像
     */
    @PostMapping("/generations")
    public Result<ImageGenerationResponse> generateImage(@RequestBody @Valid ImageGenerationRequest request,
                                                          HttpServletRequest httpRequest) {
        Long userId = (Long) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.unauthorized("用户未登录");
        }

        try {
            ImageGenerationResponse response = imageGenerationService.generateImage(request, userId);
            return Result.success("图像生成成功", response);
        } catch (Exception e) {
            return Result.error("图像生成失败: " + e.getMessage());
        }
    }

    /**
     * 图像生成请求DTO
     */
    @Data
    public static class ImageGenerationRequest {
        @NotBlank(message = "模型名称不能为空")
        private String model;

        @NotBlank(message = "提示词不能为空")
        private String prompt;

        @NotBlank(message = "图片比例不能为空")
        private String aspectRatio;

        private String responseFormat = "url";

        private List<String> image;
    }

    /**
     * 图像生成响应DTO
     */
    @Data
    public static class ImageGenerationResponse {
        private List<ImageData> data;
    }

    @Data
    public static class ImageData {
        private String url;
        private String b64Json;
    }
}

